package cn.fintecher.pangolin.service.repair.web;


import cn.fintecher.pangolin.common.utils.IdcardUtils;
import cn.fintecher.pangolin.common.utils.ZWDateUtil;
import cn.fintecher.pangolin.entity.elastic.IdCardInformation;
import cn.fintecher.pangolin.service.repair.model.IdCardInformationModel;
import cn.fintecher.pangolin.service.repair.respository.IdCardInformationRepository;
import com.google.common.collect.Lists;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVRecord;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

import static org.elasticsearch.index.query.QueryBuilders.matchPhraseQuery;

/**
 * Created by huyanmin on 2018/12/26.
 */
@RestController
@RequestMapping("/api/idCardInformation")
@Api(value = "身份证查询", description = "身份证查询")
public class IdCardInformationController {

    private final Logger log = LoggerFactory.getLogger(IdCardInformationController.class);
    @Autowired
    private IdCardInformationRepository idCardInformationRepository;

    @PostMapping(value = "/insertIdCardInformation")
    @ApiOperation(notes = "新增/更新身份证号", value = "新增/更新身份证号")
    public ResponseEntity<Void> insertIdCardInformation(@RequestParam String csvPath) throws IOException {
        String charset = "GBK";
        FileInputStream fileInputStream = new FileInputStream(csvPath);
        Reader reader = new InputStreamReader(fileInputStream, charset);
        Iterable<CSVRecord> records = CSVFormat.EXCEL.parse(reader);

        Map<String, IdCardInformation> resourceMap = new HashMap<>();
        for (CSVRecord record : records) {
            if (record.getRecordNumber() == 1) {
                continue;
            }
            IdCardInformation information = new IdCardInformation();
            information.setLocation(record.get(0));
            information.setIdCardPeriod(record.get(1));
            information.setOperatorTime(ZWDateUtil.getNowDateTime());
            resourceMap.put(information.getIdCardPeriod(), information);
        }
        if (resourceMap.size() > 0) {
            Lists.partition(new ArrayList<>(resourceMap.values()), 5000).stream().forEach(idCardInformations -> idCardInformationRepository.saveAll(idCardInformations));
        }
        return ResponseEntity.ok().build();
    }


    @GetMapping(value = "/searchIdCardInformation")
    @ApiOperation(notes = "查询身份证信息", value = "查询身份证信息")
    public ResponseEntity<IdCardInformationModel> searchIdCardInformation(@RequestParam String idCard) throws Exception {

        IdCardInformationModel idCardInformationModel = new IdCardInformationModel();
        if(Objects.nonNull(idCard)){
            String number;
            if(idCard.length() > 6){
                if(idCard.length() > 15){
                    String sex = IdcardUtils.getGenderByIdCard(idCard);
                    idCardInformationModel.setSex(sex);
                }
                if(idCard.length() >= 14) {
                    String birthday = idCard.substring(6,14);
                    idCardInformationModel.setBirthDay(birthday);
                }
                Short yearByIdCard = IdcardUtils.getYearByIdCard(idCard);
                if(Objects.nonNull(yearByIdCard)){
                    DateTime currentTime = new DateTime(ZWDateUtil.getNowDate());
                    Integer age = currentTime.getYear() - yearByIdCard;
                    idCardInformationModel.setAge(age);
                }
                number = idCard.substring(0,6);
            }else {
                number = idCard;
            }
            idCardInformationModel.setIdCardNumber(idCard);
            BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
            Iterable<IdCardInformation> all = idCardInformationRepository.search(queryBuilder.must(matchPhraseQuery("idCardPeriod", number)));
            if(all.iterator().hasNext()){
                all.forEach(idCardInformation -> {
                    idCardInformationModel.getCertificationPlace().add(idCardInformation.getLocation());
                });
            }
        }
        return ResponseEntity.ok(idCardInformationModel);
    }
}
